﻿using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Huioo.Learning.Logging.ConsoleAppWithSerilog
{
    /// <summary>
    /// 日志管理器，用于全局管理不同名称的日志实例
    /// </summary>
    public static class LoggerManager
    {
        private static readonly Dictionary<string, LoggerComponent> _loggers = new Dictionary<string, LoggerComponent>();
        private static readonly object _lock = new object();

        /// <summary>
        /// 获取或创建指定名称的日志组件
        /// </summary>
        /// <param name="name">日志名称，用于配置路径</param>
        /// <param name="baseDirectory">日志基础目录</param>
        /// <param name="minimumLevel">最小日志级别</param>
        /// <returns>日志组件实例</returns>
        public static LoggerComponent GetLogger(string name, string baseDirectory = "Logs",
            LogEventLevel minimumLevel = LogEventLevel.Information)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new ArgumentException("日志名称不能为空或空白", nameof(name));

            lock (_lock)
            {
                if (!_loggers.ContainsKey(name))
                {
                    _loggers[name] = new LoggerComponent(name, baseDirectory, minimumLevel);
                }

                return _loggers[name];
            }
        }

        /// <summary>
        /// 释放指定名称的日志组件
        /// </summary>
        /// <param name="name">日志名称</param>
        public static void ReleaseLogger(string name)
        {
            lock (_lock)
            {
                if (_loggers.TryGetValue(name, out var logger))
                {
                    logger.Dispose();
                    _loggers.Remove(name);
                }
            }
        }

        /// <summary>
        /// 释放所有日志组件
        /// </summary>
        public static void ReleaseAllLoggers()
        {
            lock (_lock)
            {
                foreach (var logger in _loggers.Values)
                {
                    logger.Dispose();
                }
                _loggers.Clear();
            }
        }
    }
}
